/**
 * @author hieu
 */

var dashboard = {
	_store : {
		popupId : "popup-jiohealth",
		variable : {
			timeout_alert : null,
			ingoreErrorMessage : false,
		},
	},
	_all_popup : {},
	_show_popup : {},
	
	
	_active_popup : function(popup_id, title, content, option) {
		var popup = dashboard.get_ele(popup_id);
		// check and remove element first
		if (dashboard.is_ele(popup)) {
			$(popup).modal('show');
		} else {
			$("<div></div>").attr({
				'id' : popup_id,
				'class' : 'modal fade hide',
			}).appendTo('body');
			popup = dashboard.get_ele(popup_id);
			// setup header for popup
			$(popup).append(dashboard._theme_popup(popup_id, title));
			// add content for popup
			$(popup).append(content);
			// show popup
			$(popup).modal('show');
		}
	},

	_theme_popup : function(popup_id, title){
		var content = dashboard.join
		('<div class="modal-header">')
			('<button type="button" class="close" data-dismiss="modal" aria-hidden="true">')
				('×')
			('</button>')
			('<h3>' + title + '</h3>')
		('</div>')
		();
		return content;
	}

};


dashboard.addListener = function(obj, eventName, listener) {
 if(obj.addEventListener) {
  obj.addEventListener(eventName, listener, false);
 } else {
  obj.attachEvent("on" + eventName, listener);
 }
};

/**
 * @param popup_id this is id of pop
 * @param title title of pop up
 * @param content of pop up
 */
dashboard.show_popup = function(popup_id, title, content, option){
	dashboard._active_popup(popup_id, title, content, option);
};

dashboard.get_top_page = function() {
	if(dashboard.is_exists(window.pageYOffset)) {
		return window.pageYOffset;
	}
	if(dashboard.is_exists(document.compatMode) && document.compatMode != 'BackCompat') {
		return document.documentElement.scrollTop;
	}
	if(dashboard.is_exists(document.body)) {
		scrollPos = document.body.scrollTop;
	}
	return 0;
};
dashboard.enter = function(id, cb) {
	if(cb) {
		if(!dashboard.is_exists(dashboard._store.variable['key_listener'])) {
			dashboard._store.variable['key_listener'] = 0;
		}
		jQuery(id).keydown(function(event) {
			if(event.keyCode == 13) {
				dashboard._store.variable['key_listener'] = setTimeout(cb, 10);
			} else {
				clearTimeout(shop._store.variable['key_listener']);
			}
		});
	}
};
dashboard.is_arr = function(arr) {
	return (arr != null && arr.constructor == Array);
};

dashboard.is_str = function(str) {
	return (str && (/string/).test( typeof str));
};

dashboard.is_func = function(func) {
	return (func != null && func.constructor == Function);
};

dashboard.is_num = function(num) {
	var num = Number(num);
	return (num != null && !isNaN(num));
};

dashboard.is_int = function(x) {
	var y = parseInt(x);
	if(isNaN(y))
		return false;
	return x == y && x.toString() == y.toString();
};

dashboard.is_obj = function(obj) {
	return (obj != null && obj instanceof Object);
};

dashboard.is_exists = function(obj) {
	return (obj != null && obj != undefined && obj != "undefined");
};

dashboard.is_blank = function(str) {
	return (dashboard.util_trim(str) == "");
};

dashboard.is_email = function(str) {
	return (/^[a-z-_0-9\.]+@[a-z-_=>0-9\.]+\.[a-z]{2,3}$/i).test(dashboard.util_trim(str));
};

dashboard.is_username = function(value) {
	return (value.match(/^[0-9]/) == null) && (value.search(/^[0-9_a-zA-Z]*$/) > -1);
};

dashboard.is_link = function(str) {
	return (/(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/).test(dashboard.util_trim(str));
};

dashboard.is_image = function(imagePath) {
	var fileType = imagePath.substring(imagePath.lastIndexOf("."), imagePath.length).toLowerCase();
	return (fileType == ".gif") || (fileType == ".jpg") || (fileType == ".png") || (fileType == ".jpeg");
};

dashboard.is_ff = function() {
	return (/Firefox/).test(navigator.userAgent);
};

dashboard.is_ie = function() {
	return (/MSIE/).test(navigator.userAgent);
};

dashboard.is_ie6 = function() {
	return (/MSIE 6/).test(navigator.userAgent);
};

dashboard.is_ie7 = function() {
	return (/MSIE 7/).test(navigator.userAgent);
};

dashboard.is_ie8 = function() {
	return (/MSIE 8/).test(navigator.userAgent);
};

dashboard.is_chrome = function() {
	return (/Chrome/).test(navigator.userAgent);
};

dashboard.is_opera = function() {
	return (/Opera/).test(navigator.userAgent);
};

dashboard.is_safari = function() {
	return (/Safari/).test(navigator.userAgent);
};

dashboard.is_ipad = function() {
	return (/iPad/).test(navigator.userAgent);
};

dashboard.is_ele = function(ele) {
	return (ele && ele.tagName && ele.nodeType == 1);
};
dashboard.isNumberKey = function(evt) {
	var charCode = (evt.which) ? evt.which : evt.keyCode;
	if (charCode > 31 && (charCode < 48 || charCode > 57))
		return false;
	return true;
};
dashboard.redirect = function(url) {
	window.location = url;
};
dashboard.join = function(str) {
	var store = [str];
	return function extend(other) {
		if(other != null && 'string' == typeof other) {
			store.push(other);
			return extend;
		}
		return store.join('');
	};
};

/**
 * Utils
 */
dashboard.util_trim = function(str) {
	return (/string/).test( typeof str) ? str.replace(/^\s+|\s+$/g, "") : "";
};

dashboard.util_random = function(a, b) {
	return Math.floor(Math.random() * (b - a + 1)) + a;
};

dashboard.get_ele = function(id) {
	return document.getElementById(id);
};
dashboard.util_isValidCode = function(txt) {
	var invalidCode = "`~!@#$%^&*()-_=+\\|[{]};:'\",<.>/?";
	for(var i = 0; i < invalidCode.length; i++) {
		for(var j = 0; j < txt.length; j++) {
			if(txt.charAt(j) == invalidCode.charAt(i)) {
				return false;
			}
		}
	}
	return true;
};
dashboard.util_isValidCode_lite = function(txt) {
	var invalidCode = "'\"";
	for(var i = 0; i < invalidCode.length; i++) {
		for(var j = 0; j < txt.length; j++) {
			if(txt.charAt(j) == invalidCode.charAt(i)) {
				return false;
			}
		}
	}
	return true;
};

dashboard.util_isValidCodeForName = function(txt) {
	var invalidCode = "`~!@#$%^&*()-_=+\\|[{]};:\",<.>/?";
	for(var i = 0; i < invalidCode.length; i++) {
		for(var j = 0; j < txt.length; j++) {
			if(txt.charAt(j) == invalidCode.charAt(i)) {
				return false;
			}
		}
	}
	return true;
};
dashboard.util_containsNumber = function(txt) {
	var seriesNumber = "0123456789";
	for(var i = 0; i < seriesNumber.length; i++) {
		for(var j = 0; j < txt.length; j++) {
			if(txt.charAt(j) == seriesNumber.charAt(i)) {
				return true;
			}
		}
	}
	return false;
};
dashboard.util_isValidateEmail = function validateEmail(email) {
	if(email == "") {
		return false;
	}
	var firstChar = email.substr(0,1);
	var num = Number(firstChar);
	if (firstChar == "." || (!isNaN(num))) {
		return false;
	}
	
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	if (!filter.test(email)) {
		return false;
	} else {
		//The dot can not before @
		var idx = email.indexOf("@");
		if (idx > 0 && email.substr(idx - 1, 1) == ".") {
		   	return false;
		}
		
		return true;
	}
};
dashboard.util_string = {
	startsWith : function(key, str) {
		if(dashboard.util_string.isEmpty(str))
			return false;
		return str.indexOf(key) == 0;
	},

	endsWith : function(postfix, string) {
		if(this.isEmpty(string) || this.isEmpty(postfix))
			return false;
		return string.lastIndexOf(postfix) == string.length - postfix.length;
	},
	/**
	 *
	 * @param key
	 * @param key_next
	 * @param str
	 */
	endsWithString : function(key, key_next, str) {
		if(dashboard.util_string.isEmpty(key) || dashboard.util_string.isEmpty(key_next) || dashboard.util_string.isEmpty(str))
			return false;
		var s = str.substring(0, str.indexOf(key_next));
		return s.lastIndexOf(key) == (str.indexOf(key_next) - 1);
	},
	isEmpty : function(string) {
		return string == null || string.length == 0;
	},
};
dashboard.cookie = {
	clearAllCookies : function() {
		var cookies = document.cookie.split(";");
		var ck = "";
		for(var i = 0; i < cookies.length; i++) {
			ck = jQuery.trim(cookies[i]).split("=")[0];
			//get cookie name
			if((ck.substr(0, 3) == config_variable.cookie.prefix) && (ck != config_variable.cookie.remember_me) && (ck != config_variable.cookie.login_id)) {
				jQuery.cookie(ck, null, {
					path : '/'
				});
			} else if(ck == config_variable.cookie.authentication_key || ck == config_variable.cookie.is_admin) {
				jQuery.cookie(ck, null, {
					path : '/'
				});
			}
		}
	},
};
/**
 *
 * @param {Object} str
 * Need <div id="alert"></div>
 */

dashboard.show_alert = function(str) {
	clearTimeout(dashboard._store.variable.timeout_alert);
	var content = dashboard.join
	('<div class="alert alert-block alert-error fade in">')
	('<a href="#" data-dismiss="alert" class="close">×</a>')
	('<span>' + str + '</span>')
	('</div>')();
	$('#alert').html('').append(content);
};
dashboard.show_alert_fix = function(id, str) {
	var place = $(id);
	var content = dashboard.join
	('<div class="alert alert-block alert-error fade in">')
	('<a href="#" data-dismiss="alert" class="close">×</a>')
	('<span>' + str + '</span>')
	('</div>')();
	place.html('').append(content);
};
dashboard.show_alert_fix_time = function(id, str) {
	clearTimeout(dashboard._store.variable.timeout_alert);
	var place = $(id);
	var content = dashboard.join
	('<div class="alert alert-block alert-error fade in">')
	('<a href="#" data-dismiss="alert" class="close">×</a>')
	('<span>' + str + '</span>')
	('</div>')();
	place.html('').append(content);
};
dashboard.showAlert = function(id, str) {
	clearTimeout(dashboard._store.variable.timeout_alert);
	var place = $('#'+id);
	var content = dashboard.join
	('<div class="alert alert-block alert-error fade in">')
	('<a href="#" data-dismiss="alert" class="close">×</a>')
	('<span>' + str + '</span>')
	('</div>')();
	place.html('').append(content);
	
	dashboard._store.variable.timeout_alert = setTimeout(function() {
		$('#'+id + ' .alert').alert('close');
	}, 3000);
};
dashboard.show_success = function(id, str) {
	var place = $(id);
	var content = dashboard.join
	('<div class="alert alert-block alert-success fade in">')
	('<a href="#" data-dismiss="alert" class="close">×</a>')
	('<span>' + str + '</span>')
	('</div>')();
	place.html('').append(content);
};
/**
 * Display loading gif
 * When waiting response from server
 * @param the id of div
 * Require a div which have same id in template
 */
dashboard.show_loading = function(id) {
	jQuery("#" + id).html("<div align='center'><img src='images/ajax-loading.gif' />&nbsp;Loading...</div>");
};

dashboard.time_out_close_alert = function(str) {
	$(".alert").alert('close');
};

dashboard.client_include = function(id, url) {
	var req = false;
	// For Safari, Firefox, and other non-MS browsers
	if(window.XMLHttpRequest) {
		try {
			req = new XMLHttpRequest();
		} catch (e) {
			req = false;
		}
	} else if(window.ActiveXObject) {
		// For Internet Explorer on Windows
		try {
			req = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				req = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				req = false;
			}
		}
	}
	var element = document.getElementById(id);
	if(!element) {
		alert("Bad id " + id + "passed to clientSideInclude." + "You need a div or span element " + "with this id in your page.");
		return;
	}
	if(req) {
		// Synchronous request, wait till we have it all
		req.open('GET', url, false);
		req.send(null);
		element.innerHTML = req.responseText;
	} else {
		element.innerHTML = "Sorry, your browser does not support " + "XMLHTTPRequest objects. This page requires " + "Internet Explorer 5 or better for Windows, " + "or Firefox for any system, or Safari. Other " + "compatible browsers may also exist.";
	}
};

dashboard.generate_path = function(arrParams) {
	var path = domainWS;
	for(var i = 0; i < arrParams.length; i++) {
		if(i < (arrParams.length - 1)) {
			path += arrParams[i] + "/";
		} else {
			path += arrParams[i] + "?rnd=" + Math.random();
		}
	}
	return path;
};
dashboard.getURLParameter = function(name) {
	return decodeURIComponent((location.search.match(RegExp("[?|&]"+name+'=(.+?)(&|$)'))||[,null])[1]);
};

var LoadingScreen = {
	start : function() {
		var self = this;
		if(!("webkitMask" in document.body.style)) {
			document.getElementById("loading_screen_background").style.backgroundImage = "none";
		}

		self._resize();
		if(dashboard.is_ie()) {
			window.attachEvent("onload", function() {
				LoadingScreen.stop();
			});
		} else {
			window.addEventListener("resize", LoadingScreen._resize, false);
		}
	},

	stop : function() {
		document.getElementById("loading_screen").style.display = "none";
	},

	_resize : function() {
		var window_height = $(window).height();
		document.getElementById('loading_screen').style.height = window_height + "px";
		document.getElementById('loading_screen_logo').style.paddingTop = (window_height * .43) + "px";
	}
};


/**
 * Modify function max min of array.
 */
dashboard.arrayMax = function( array ){
    return Math.max.apply( Math, array );
};

dashboard.arrayMin = function( array ){
    return Math.min.apply( Math, array );
};

dashboard.getUrlVars = function() {
	var vars = [], hash;
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	for(var i = 0; i < hashes.length; i++) {
		hash = hashes[i].split('=');
		vars.push(hash[0]);
		vars[hash[0]] = hash[1];
	}
	return vars;
};
dashboard.getUrlVar = function(name) {
	return dashboard.getUrlVars()[name];
};

/*
 * Set up ajax handle network code 
 */
$.ajaxSetup({
	// beforeSend : function(xhr) {
		// xhr.setRequestHeader("Authorization", "Basic " + AUTHENTICATION_KEY);
		// dashboard.security.checkStatusAccessTokenIdle();
	// },
	// complete: function(response, textStatus) {    
	    // if(response.status == 0) {
	    	// dashboard.cookie.clearAllCookies();
	     	// window.location = LOGIN_PAGE;
	    // } 
	// }
});
/**
 * 
 */
$.validator.addMethod('filesize', function(value, element, param) {
    // param = size (en bytes) 
    // element = element to validate (<input>)
    // value = value of the element (file name)
    return this.optional(element) || (element.files[0].size <= param);
}, jQuery.format("File must be less than {0}"));